package org.fly4j.part1.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * Created by 37284 on 2016/1/2.
 *
 * 对类的一些操作
 */
public class ClassUtils {
    private static final  Logger LOGGER = LoggerFactory.getLogger(ClassUtils.class);

    /**
     * 获得类加载器
     */
    public static ClassLoader getClassLoader(){
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载某个类
     * 第二个布尔值表示是否初始化 类的 静态代码块
     */
    public static Class<?> loadClass(String className,boolean isInitializes){
       Class<?> cls = null;
        try {
            LOGGER.info("load class ===> "+className);
            cls = Class.forName(className,isInitializes,getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error("load class failure .",e);
            throw new RuntimeException();
        }
        return cls;
    }

    /**
     * 加载某个包下的类
     * 根据包名转换为文件路径
     */
    public static Set<Class<?>> loadClassSet(String packageName){
        Set<Class<?>> classSet = new HashSet<>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            while(urls.hasMoreElements()){
                URL url = urls.nextElement();
                 if(url!=null){
                   String protocol = url.getProtocol();
                    if(protocol.equals("file")){
                      String packagePath =  url.getPath().replace("%20"," ");
                        addClass(classSet,packagePath,packageName);
                    }else if (protocol.equals("jar")){
                        //读取jar包里面的类
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if(jarURLConnection!=null){
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if(jarFile!=null){
                                Enumeration<JarEntry> jarEntrys = jarFile.entries();
                                while(jarEntrys.hasMoreElements()){
                                  JarEntry jarEntry =   jarEntrys.nextElement();
                                   String jarEntryName =  jarEntry.getName();
                                    if(jarEntryName.endsWith(".class")){
                                        String className = jarEntryName.substring(0,jarEntryName.lastIndexOf(".")).replace(".","/");
                                        doAddClass(classSet,className);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.error("get class set failure .",e);
           throw new RuntimeException(e);
        }
        return classSet;
    }

    private static void addClass(Set<Class<?>> classSet,String packagePath,String packageName){

        File[] files = new File(packagePath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class") || file.isDirectory());
            }
        });

        for(File file : files){
            String fileName = file.getName();
            //有可能是目录
            if(file.isFile()){
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if(StringUtil.isNotEmpty(packageName)){
                    className = packageName+ "." +className;
                 }
                 doAddClass(classSet,className);

            }else{
                 String subPackagePath = fileName;
                if(StringUtil.isNotEmpty(packagePath)){
                    subPackagePath = packagePath + "/" + subPackagePath;
                }

                String subPackageName = fileName;
                if(StringUtil.isNotEmpty(packagePath)){
                    subPackageName = packageName + "." + subPackageName;
                }

                addClass(classSet,subPackagePath,subPackageName);
            }
        }

    }

    private static void doAddClass(Set<Class<?>> classSet, String className) {
        Class<?> cls = loadClass(className,false);
        classSet.add(cls);
    }
}
